package com.licq.hongmeng.net;



import com.google.gson.JsonParseException;
import ohos.app.Context;
import retrofit2.Call;
import retrofit2.HttpException;

import java.io.InterruptedIOException;
import java.lang.ref.WeakReference;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.text.ParseException;

import javax.net.ssl.SSLHandshakeException;


/**
 * 兼容之前的继承方式，抽离统一处理的代码
 *
 * @param <T>
 */
public abstract class RxNetObserver<T> {

    protected final int RESPONSE_CODE_OK =200;
    protected WeakReference<Context> con;

    public RxNetObserver(Context context) {
        this.con = new WeakReference<>(context);
    }

    /**
     * 订阅，回调后，在UI层添加到队列中，界面销毁时统一关闭请求，防止内存泄漏
     *
     * @param disposable
     */
    public abstract void onSubscribed(Call disposable);

    /**
     * 访问成功的回调，根据不同的方式继承或是泛型，根据返回的实体类进行处理
     *
     * @param t
     */
    public abstract void onSuccess(T t, String errorMsg);

    /**
     * 失败回调
     *
     * @param msg
     */
    public abstract void onFail( String msg);

    /**
     * 访问服务器错误处理
     *
     * @param t
     */
    protected final void error( Throwable t) {
        if (t == null) {
            try {
                onFail("onError method parameter is empty");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return;
        }
        try {
            if (t instanceof SocketTimeoutException) {//请求超时
                onFail("请求超时");
            } else if (t instanceof ConnectException) {//网络连接超时
                onFail("网络连接超时");
            } else if (t instanceof SSLHandshakeException) {//安全证书异常
                onFail("安全证书异常");
            } else if (t instanceof HttpException) {//请求的地址不存在
                int code = ((HttpException) t).code();
                switch (code) {
                    case 401:
                    case 403:
                        onFail("权限错误");
                        break;
                    case 404:
                        onFail("接口未找到");
                        break;
                    case 408:
                    case 504:
                    case 500:
                    case 502:
                    case 503:
                    default:
                        onFail("服务器异常");
                        break;
                }
            } else if (t instanceof UnknownHostException) { //域名解析失败 无网络
                onFail("域名解析失败");
            } else if (t instanceof InterruptedIOException) { //连接超时
                onFail("连接超时");
            } else if (t instanceof JsonParseException
                    || t instanceof ParseException) { //解析错误
                onFail("解析错误");
            }
        } catch (Exception e2) {
            e2.printStackTrace();
            try {
                onFail("请求出错");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
